package RCp2;

import java.net.*;
import java.io.*;

// Cliente de eco UDP
public class ClienteTCP {

    public static void main(String[] args) throws IOException {
        String maquina = "localhost";
        int porto = 8080;
        String mensaxe = "OLA MANOLA";

        // Obte-lo enderezo do servidor
        InetAddress enderezo = InetAddress.getByName(maquina);
        // Establecemo-la conexion co servidor ao crear o socket
        Socket socket = new Socket(enderezo, porto);
        // Establecemos un timeout de 30s
        socket.setSoTimeout(30000);
        try {

            System.out.println("Socket creado: + " + socket.toString());

            // Establecemo-la canle de entrada
            BufferedReader buffIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // Establecemo-la canle de saida
            PrintWriter buffOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

            System.out.println("Establecidas as canles de entada e saida");

            // Enviamo-la mensaxe
            buffOut.println(mensaxe);
            System.out.println("Mensaxe enviada... " + mensaxe);
            // Lemos a resposta do servidor
            String str = buffIn.readLine();
            System.out.println("Mensaxe recibida: " + str);
        } catch (Exception e) {
            System.err.println("Erro: " + e.getMessage());
            e.printStackTrace();
        } finally {
            socket.close();
        }
    }
}
